package com.iot08.common.utils;

import com.iot08.common.entity.util.MailServer;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.*;

@Slf4j
public class MailUtil {

    private static final String SMTP_HOST = "mail.smtp.host";
    private static final String SMTP_PORT = "mail.smtp.port";
    private static final String SMTP_AUTH = "mail.smtp.auth";

    public enum Pattern {
        DEFAULT, POMO, IRIST, DOKI
    }

    /**
     * 发送邮件给单收件人
     *
     * @param to      收件人
     * @param subject 标题
     * @param content 正文
     * @param isHtml  是否为HTML
     */
    public static void sendToSingle(String to, String subject, String content, boolean isHtml, MailServer mail) {
        List<String> list = new ArrayList<String>();
        list.add(to);
        send(list, subject, content, isHtml, mail);
    }


    /**
     * 使用默认的设置账户发送邮件
     *
     * @param tos     收件人列表
     * @param subject 标题
     * @param content 正文
     * @param isHtml  是否为HTML
     */
    public static void send(Collection<String> tos, String subject, String content, boolean isHtml, MailServer mailServer
    ) {
        try {
            sendAfterAuth(tos, subject, content, isHtml, mailServer);
        } catch (MessagingException e) {
            e.printStackTrace();
            log.error("Send mail error!", e);
        } catch (UnsupportedEncodingException e) {
            log.error("Send mail error!", e);
            e.printStackTrace();
        } catch (Exception e) {
            log.error("Send mail error!", e);
            e.printStackTrace();
        }
    }

    /**
     * 发送邮件给多人
     *
     * @param mailServer 邮件认证对象
     * @param tos        收件人列表
     * @param subject    标题
     * @param content    正文
     * @param isHtml     是否为HTML格式
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static void sendAfterAuth(Collection<String> tos, String subject, String content, boolean isHtml, final MailServer mailServer
    ) throws MessagingException, UnsupportedEncodingException, GeneralSecurityException {
        Properties p = new Properties();
        p.put(SMTP_HOST, mailServer.getHost());
        p.put(SMTP_PORT, mailServer.getPort());
        p.put(SMTP_AUTH, mailServer.isAuth());
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.ssl.trust", mailServer.getHost());
        if (mailServer.getPort().equals(465)) {//SSL加密端口
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);
        }

        //认证登录
        Session session = Session.getInstance(p,
                mailServer.isAuth() ?
                        new Authenticator() {
                            @Override
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailServer.getUsername(), mailServer.getPassword());
                            }
                        } : null
        );

        Message mailMessage = new MimeMessage(session);
        //mailMessage.setFrom(new InternetAddress(mailProperties.getFrom()));
        mailMessage.setFrom(new InternetAddress(mailServer.getFromWhere(), mailServer.getPersonal()));
        mailMessage.setSubject(MimeUtility.encodeText(subject, MimeUtility.mimeCharset("utf-8"), null));
        mailMessage.setSentDate(new Date());

        if (isHtml) {
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(content, "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            mailMessage.setContent(mainPart);
        } else {
            mailMessage.setText(content);
        }

        for (String to : tos) {
            log.info("Start {} Send mail to {} successed message:{}", mailServer.getUsername(), to, mailMessage);
            mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(mailMessage);
            log.info("Finished {} Send mail to {} successed", mailServer.getUsername(), to);
            //log.info("{} Send mail to {} successed",mailAccount.getUsername(),to);
        }
    }

	/*public static void main(String[] args) {
		MailServer mailServer = new MailServer();
		mailServer.setFromWhere("appsupport@moochies.com");
		mailServer.setPassword("Caveman1");
		mailServer.setUsername("appsupport@moochies.com");
		mailServer.setPort(587);
		mailServer.setPersonal("moochies");
		mailServer.setHost("smtp.office365.com");
	}*/

}
